// Store 统一导出

export { useUserStore } from './user'
export { useAppStore } from './app'
export { useAccountStore } from './account'
export { useCategoryStore } from './category'

// Store 初始化和清理工具
import { useUserStore } from './user'
import { useAppStore } from './app'
import { useAccountStore } from './account'
import { useCategoryStore } from './category'

/**
 * 初始化所有 Store
 */
export const initStores = async () => {
  const userStore = useUserStore()
  const appStore = useAppStore()

  // 初始化用户状态（从存储中恢复）
  userStore.initUserState()

  // 初始化应用状态
  appStore.initAppState()

  // 如果用户已登录，加载应用配置
  if (userStore.isLoggedIn) {
    try {
      await appStore.loadSystemConfig()
    } catch (error) {
      console.error('加载系统配置失败:', error)
    }
  }
}

/**
 * 清理所有 Store 状态
 */
export const clearAllStores = () => {
  const userStore = useUserStore()
  const appStore = useAppStore()
  const accountStore = useAccountStore()
  const categoryStore = useCategoryStore()

  userStore.clearUserState()
  appStore.resetAppState()
  accountStore.resetState()
  categoryStore.resetState()
}

/**
 * 登录后初始化
 */
export const initAfterLogin = async () => {
  const appStore = useAppStore()
  const categoryStore = useCategoryStore()
  const accountStore = useAccountStore()

  try {
    // 并行加载基础数据
    await Promise.all([
      appStore.loadSystemConfig(),
      categoryStore.loadCategories(),
      accountStore.loadAccountStats()
    ])

    // 检查版本更新
    appStore.checkUpdate().catch(console.error)

  } catch (error) {
    console.error('登录后初始化失败:', error)
    throw error
  }
}

/**
 * 退出登录清理
 */
export const cleanupAfterLogout = () => {
  const accountStore = useAccountStore()
  const categoryStore = useCategoryStore()

  // 清理业务数据
  accountStore.resetState()
  categoryStore.resetState()

  // 清理本地存储中的敏感数据
  uni.removeStorageSync('master_password')
  uni.removeStorageSync('encrypt_config')
  uni.removeStorageSync('local_accounts')
}

/**
 * 设置主密码
 */
export const setMasterPassword = (password: string, encryptMethod?: string) => {
  const accountStore = useAccountStore()

  accountStore.setEncryptConfig({
    masterPassword: password,
    method: encryptMethod as any
  })

  // 缓存主密码（会话级别）
  uni.setStorageSync('master_password', password)
}

/**
 * 获取缓存的主密码
 */
export const getCachedMasterPassword = (): string | null => {
  return uni.getStorageSync('master_password') || null
}

/**
 * 清除主密码缓存
 */
export const clearMasterPasswordCache = () => {
  uni.removeStorageSync('master_password')

  const accountStore = useAccountStore()
  accountStore.setEncryptConfig({ masterPassword: '' })
}

/**
 * 检查是否需要输入主密码
 */
export const checkNeedMasterPassword = (): boolean => {
  const userStore = useUserStore()
  const cachedPassword = getCachedMasterPassword()

  return userStore.isLoggedIn && !cachedPassword
}

// 类型导出
export type {
  UserInfo,
  LoginData,
  RegisterData
} from './user'

export type {
  Account,
  AccountStats
} from './account'

export type {
  Category,
  CategoryStats
} from './category'